<?php


namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use think\Validate;
use think\facade\Cache;
use DateTime;
use DateInterval;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory as AlipayFactory;

class Index extends Homebase
{
    protected $city_array;


    protected function initialize()
    {
        parent::initialize();
        $this->city_array = array('北京市', '上海市', '天津市', '重庆市');
        //    city  上海市
        //    longitude 117.120000
        //    latitude  36.650200
    }



    /**
     * 获取openid
     */
    public function wxLogin()
    {
        $code = $this->request->param("code");
        $appId = config('wechat.appID');
        $secret = config('wechat.AppSecret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = lmcurl($url);
        msg(0, "成功", $res);
    }
    /**
     * 获取支付宝openid  alipay.system.oauth.token
     */
    public function wxLoginzfb()
    {
        $code = $this->request->param("code");
        $appId = config('wechat.zfb_appId');
        $secret = config('wechat.zfb_secret');
        $now=date('Y-m-d H:i:s');
        
        //        &refresh_token=201208134b203fe6c11548bcabd8da5bb087a83b
        $url = 'https://openapi.alipay.com/gateway.do?
        charset=UTF-8
        &method=alipay.system.oauth.token
        &format=json
        &sign='.'XRYP7W4IcC1P3ZktNbPkFfm/Qb4VXD85tFTLFw1o3XtBN2aiVdup8CW0zIpmbuqy+Tb9ZociFz4XLKtilYNSMYYKz01UivrJkFUcHu7arY6TOej1vdhH4RDuI9N1sUwTdatx3/X9BtYHP4yASP1MJ+1urF/hQ/raeIx5NnIVdl0AxOtmOA1FB+VqLW8nR2q6aqkZVgdUw418R6pKE6kmdMkZsCgAjdL1Jl/g3BtO56whVnGo6q9pZuZuljs7OmfAGAj0J47EQHmrAQaC/ZcCF+pHL7Svjm94mUDr/ggwKmmlMyEsvWWvQYimUlCmDepagq3pKAULjrHQwW3jWObWRg=='.'
        &app_id='.$appId.'
        &version=1.0
        &sign_type=RSA2
        &timestamp='.$now.'
        $code='.$code.'
        $grant_type=authorization_code';
        $res = lmcurl($url);
        msg(0, "成功", $res);
    }

    /**
     * 上传图片
     */
    // todo 转换成webp 看图片压缩
    public function upload_img()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploads');

        if ($info) {

            $logo = '/' . 'uploads' . '/' . $info->getSaveName();

            $datas = $info->getInfo();

            $img['path'] = $logo;

            $img['mime'] = $datas['type'];

            $img['name'] = $datas['name'];

            $img['size'] = $datas['size'];

            $img['sha1'] = $info->hash('sha1');

            $img['md5'] = $info->hash('md5');

            $img['driver'] = 'local';

            $img['create_time'] = time();

            $img['update_time'] = time();

            $img['status'] = 1;

            $img['ext'] = $info->getExtension();

            $id = Db::name('attachment')->insertGetId($img);
            //todo 关闭oss
//            if (config('is_oss') == 1) {
//                upload_local_file($id);
//            }
            $d = db('attachment')->where('id', $id)->find();
            if ($d['type'] == 1) {
                $d['path'] = conf("wechat", "url") . str_replace('\\', '/', $d['path']);
            } else {
                $d['path'] = conf("wechat", "url") . $d['path'];
            }
            msg(0, "获取成功", $d);

        } else {
            echo $files->getError();
        }
        //msg(0, "成功", $url);
    }

    /**
     * 获取手机号
     */
    public function getPhone()
    {
        try {
            $data = $this->request->param();
            $config = config('wechat.config');
            $app = Factory::miniProgram($config);
            $data = $app->phone_number->getUserPhoneNumber($data['code']);
            msg(0, '查询成功', $data);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    /**
     * @return void 保存用户信息微信使用
     */
    public function deuser()
    {
        $data = $this->request->param();

        $datas['openid'] = $data['openid'];

        $datas['reg_ip'] = $this->request->ip();

        $datas['mobile'] = $data['mobile'];

        $datas['nickname'] = $data['nickname'];

        $datas['avatarUrl'] = $data['avatarUrl'];

        if (isset($data['invite_id'])) {
            $datas['invite_id'] = $data['invite_id'];
        }

        $rules = [
            'openid' => 'require',
            'mobile' => 'require',
//            'nickname' => 'require',
//            'avatarUrl' => 'require',
        ];
        $message = [
            'openid.require' => 'openid必须',
            'mobile.require' => '手机必须',
//            'nickname.require' => '昵称必须',
//            'avatarUrl.require' => '头像必须',
        ];
        $validate = new Validate($rules, $message);
        $result = $validate->check($data);
        if (!$result) {
            msg(-1, '缺少信息', '');
        }
        $stmt = Db::name('member')->where('mobile', $datas['mobile'])->find();
        if ($stmt) {
            $datas['last_login_time'] = time();
            unset($datas['nickname']);
            unset($datas['avatarUrl']);
            Db::name('member')->where('mobile', $datas['mobile'])->update($datas);
            $member = Db::name('member')->where('mobile', $datas['mobile'])->find();
            if ($member['status'] == 0) {
                responseJson(-200, '用户已冻结', $member);
            }
            msg(0, '查询成功', $member);
        } else {
            $datas['create_time'] = time();
            $datas['status'] = 1;
            //一键默认登录 设置默认昵称 默认头像
            $datas['nickname'] = '用户' . rand(0000, 9999);
            $datas['avatarUrl'] = config('site.web_default_avatar');
            //邀请用户
            if (isset($data['invite_id'])) {

            }
            $user_id = Db::name('member')->insertGetId($datas);
            msg(0, '新建成功', $datas);
        }
    }
    /**
     * @return void 保存用户信息支付宝使用
     */
    public function deuser2()
    {
        $data = $this->request->param();

        $datas['zfb_open_id'] = $data['zfb_open_id'];

        $datas['reg_ip'] = $this->request->ip();

        $datas['mobile'] = $data['mobile'];

        $datas['nickname'] = $data['nickname'];

        $datas['avatarUrl'] = $data['avatarUrl'];

        if (isset($data['invite_id'])) {
            $datas['invite_id'] = $data['invite_id'];
        }

        $rules = [
            'zfb_open_id' => 'require',
            'mobile' => 'require',
//            'nickname' => 'require',
//            'avatarUrl' => 'require',
        ];
        $message = [
            'zfb_open_id.require' => 'zfb_open_id必须',
            'mobile.require' => '手机必须',
//            'nickname.require' => '昵称必须',
//            'avatarUrl.require' => '头像必须',
        ];
        $validate = new Validate($rules, $message);
        $result = $validate->check($data);
        if (!$result) {
            msg(-1, '缺少信息', '');
        }
        $stmt = Db::name('member')->where('mobile', $datas['mobile'])->find();
        if ($stmt) {
            $datas['last_login_time'] = time();
            unset($datas['nickname']);
            unset($datas['avatarUrl']);
            Db::name('member')->where('mobile', $datas['mobile'])->update($datas);
            $member = Db::name('member')->where('mobile', $datas['mobile'])->find();
            if ($member['status'] == 0) {
                responseJson(-200, '用户已冻结', $member);
            }
            msg(0, '查询成功', $member);
        } else {
            $datas['create_time'] = time();
            $datas['status'] = 1;
            //一键默认登录 设置默认昵称 默认头像
            $datas['nickname'] = '用户' . rand(0000, 9999);
            $datas['avatarUrl'] = config('site.web_default_avatar');
            //邀请用户
            if (isset($data['invite_id'])) {

            }
            $user_id = Db::name('member')->insertGetId($datas);
            msg(0, '新建成功', $datas);
        }
    }

    /**
     * 获取各项配置
     */
    public function getConfigAdmin()
    {
        $data = $this->request->param();
        if ($data['set_name'] && isset($data['set_name'])) {
            msg(0, '查询完成', config('site.' . $data['set_name']));
        }
        msg(-1, '请输入查询内容', '');
    }

    //通过坐标获取位置信息
    public function getAddressByLocation()
    {
        $data = $this->request->param();
        //当前维度 经度 搜索关键字 页数 所在市
        $data_list = getAddressByLocation2($data['latitude'], $data['longitude']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            $data_list['data']['location']['lat'] = $data['latitude'];
            $data_list['data']['location']['lng'] = $data['longitude'];
            msg(0, '查询成功', $data_list['data']);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }

    //通过市获取坐标
    public function getCityLocation()
    {
        $data = $this->request->param();
        //当前维度 经度 搜索关键字 页数 所在市
        $data_list = getLWByAddress($data['city']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            msg(0, '查询成功', $data_list['data']);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }

    //获取评价标签
    public function getCommentLabList()
    {
        $result = Db::name('comment_label')
            ->where([
                'status' => 1,
                'is_del' => 0,
            ])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $result);
    }


    //获取天气
    public function getWeatherByCity()
    {
        $address = getCityByIP();
        $data = getWeatherByCity($address['city']);
        msg(0, '查询成功', $data);
    }

    /**
     * 获取banner图
     */
    public function getBanner()
    {
        $data = $this->request->param();
        //经纬度
        if (in_array($data['city'], $this->city_array)) {
            $return_data = Db::name('banner')
                ->where(['status' => 1, 'is_del' => 0, 'province' => $data['city']])
                ->order('sort desc')
                ->select();
        } else {
            $return_data = Db::name('banner')
                ->where(['status' => 1, 'is_del' => 0, 'city' => $data['city']])
                ->order('sort desc')
                ->select();
        }
        if (!$return_data) {
            $return_data = Db::name('banner')
                ->where(['status' => 1, 'is_del' => 0, 'province_id' => 0])
                ->order('sort desc')
                ->select();
        }
        msg(0, '查询成功', $return_data);
    }

    //获取陪诊服务列表 todo 价格做处理
    public function getPzList()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];

        $return_data = Db::name('server')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        foreach ($return_data as $k => $v) {
            $return_data[$k]['tag'] = explode(',', $v['tag']);
            $return_data[$k]['price'] = getPrice($v['id'], $city);
        }
        msg(0, '查询成功', $return_data);
    }

    //获取导诊服务列表
    public function getDzList()
    {
        $data = Db::name('server2')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['tag'] = explode(',', $v['tag']);
        }
        msg(0, '查询成功', $data);
    }

    //获取接送服务列表
    public function getJsList()
    {
        $data = Db::name('server3')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        foreach ($data as $k => $v) {
            $data[$k]['tag'] = explode(',', $v['tag']);
        }
        msg(0, '查询成功', $data);
    }

    //首页推荐套餐
    public function getPackageList()
    {
        $data = Db::name('package')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        msg(0, '查询成功', $data);
    }

    //获取本市最近医院
    public function getHospitalRecently()
    {
        $data = $this->request->param();
        $where = array();
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (in_array($data['city'], $this->city_array)) {
            $where[] = ['province', '=', $data['city']];
        } else {
            $where[] = ['city', '=', $data['city']];
        }
        $return_data = Db::name('hospital')
            ->where($where)
            ->find();
        msg(0, '查询成功', $return_data);
    }

    //获取陪诊详情
    public function getServerDetail()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $server_id = $data['id'];
        $order_detail = Db::name('server')->find($server_id);
        $order_detail['price'] = getPrice($data['id'], $city);
        $order_detail['tag'] = explode(',', $order_detail['tag']);
        msg(0, '查询成功', $order_detail);
    }

    public function getPrice($server_id, $city)
    {
        $order_detail = Db::name('server')->find($server_id);
        $price_info = Db::name('server_price')->where([
            ['is_del', '=', 0],
            ['province|city', '=', $city],
            ['server_id', '=', $server_id]
        ])->find();
        if ($price_info) {
            return $price_info['price'];
        }
        return $order_detail['price'];
    }

    //获取陪诊服务评价顶部

    //获取陪诊评价列表

    //下单列表

    //获取当前位置医院列表
    public function getHospitalList()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (isset($data['search_name']) && $data['search_name']) {
            $where[] = ['name', 'like', '%' . $data['search_name'] . '%'];
        }
        if (in_array($city, $this->city_array)) {
            $where[] = ['province', '=', $data['city']];
        } else {
            $where[] = ['city', '=', $data['city']];
        }
        $return_data = Db::name('hospital')->where($where)->select();
        foreach ($return_data as $k => $v) {
            $distance = distanceHaversine($data['latitude'], $data['longitude'], $v['latitude'], $v['longitude']);
            $distance = floor($distance * 1000);
            $return_data[$k]['distance'] = $distance;
            $return_data[$k]['doctor_num'] = Db::name('doctor')->where([
                'hospita_id' => $v['id'],
                'is_del' => 0
            ])->count();
            $return_data[$k]['is_distance'] = 0;
        }
        usort($return_data, function ($a, $b) {
            return $a['distance'] - $b['distance'];
        });
        $return_data[0]['is_distance'] = 1;
        msg(0, '查询成功', $return_data);
    }

    //获取医院科室列表
    public function getDepartment()
    {
        $data = $this->request->param();
        $hospital_id = $data['hospital_id'];
        $_list = Db::name('department')
            ->where(['is_del' => 0, 'hospital_id' => $hospital_id, 'pid' => 0])
            ->order('sort desc')
            ->select();
        foreach ($_list as $k => $v) {
            $_list[$k]['is_able'] = 1;
        }
        //  $_list2 = listToTree($_list, $pk = 'id', $pid = 'pid', $child = 'child');
        msg(0, '查询成功', $_list);
    }

    //获取科室列表2
    public function getDepartment2()
    {
        $data = $this->request->param();
        $_list = Db::name('department')
            ->where(['is_del' => 0, 'pid' => $data['id']])
            ->order('sort desc')
            ->select();
        foreach ($_list as $k => $v) {
            $_list[$k]['is_able'] = 1;
        }
        //  $_list2 = listToTree($_list, $pk = 'id', $pid = 'pid', $child = 'child');
        msg(0, '查询成功', $_list);
    }

    //获取导诊服务详情
    public function server2Detail()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];

        $order_detail = Db::name('server2')->find();
        $order_detail['tag'] = explode(',', $order_detail['tag']);
        msg(0, '查询成功', $order_detail);
    }

    //导诊服务评价顶部
    //导诊评价列表

    //支持导诊地区
    public function server2Area()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $city_list = Db::name('hospital')
            ->field('real_city,count(*) as num')
            ->group('real_city')
            ->where(['is_del' => 0, 'status' => 1])
            ->select();
        msg(0, '查询成功', $city_list);
    }

    //疾病列表
    public function getCbingList()
    {
        $data_list = Db::name('cbing')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //推荐医院城市导诊选择
    public function getHospital2()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $where[] = ['real_city', '=', $city];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (isset($data['cbing_id']) && $data['cbing_id']) {

        }
        $data_list = Db::name('hospital')
            ->order('sort desc')
            ->where($where)
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['distance'] = 560;
            $data_list[$k]['doctor_num'] = 12;
        }
        msg(0, '查询成功', $data_list);

    }

    //推荐医生城市/医院
    public function getDoctorList()
    {
        $data = $this->request->param();
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        if (isset($data['city']) && $data['city']) {
            $where[] = ['real_city', '=', $data['city']];
        }
        if (isset($data['hospital_id']) && $data['hospital_id']) {
            $where[] = ['hospita_id', '=', $data['hospital_id']];
        }
        if (isset($data['cbing_id']) && $data['cbing_id']) {

        }

        $data_list = Db::name('doctor')->where($where)
            ->order('sort desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $department_info = Db::name('department')->find($v['department_id']);
            $data_list[$k]['department'] = $department_info['name'];
        }
        msg(0, '查询成功', $data_list);
    }

    //医院详情
    public function hospItalDetail()
    {
        $data = $this->request->param();
        $return_data = Db::name('hospital')->find($data['id']);
        $return_data['distance'] = 560;
        $return_data['doctor_num'] = 12;
        msg(0, '查询成功', $return_data);
    }

    //医生详情
    public function doctorDetail()
    {
        $data = $this->request->param();
        $doctor_id = $data['id'];
        $doctor_info = Db::name('doctor')->find($doctor_id);
        $hospital_info = Db::name('hospital')->find($doctor_info['hospital_id']);
        $department = Db::name('department')->find($doctor_info['department_id']);
        $doctor_info['hospital'] = $hospital_info['name'];
        $doctor_info['hospital_level'] = explode(',', $hospital_info['tag']);
        $doctor_info['department'] = $department['name'];
        msg(0, '查询成功', $doctor_info);
    }

    //获取最近四天日期 并显示周几
    public function getData()
    {
        // 创建一个 DateTime 对象，表示当前日期
        $currentDate = new DateTime();
        // 创建一个数组来保存往后四天的日期和星期几
        $dates = [];
        // 循环四次，每次增加一天
        for ($i = -1; $i < 3; $i++) {
            // 克隆当前日期对象
            $date = clone $currentDate;

            // 增加 $i+1 天（因为 $i 是从 0 开始的）
            $date->add(new DateInterval('P' . ($i + 1) . 'D'));

            // 获取日期的字符串表示
            $dateString = $date->format('m-d');

            // 获取星期几，使用 'l' 格式化字符表示完整的星期名称
            $dayOfWeek = $date->format('w');
            $weekMap = [0 => '周日', 1 => '周一', 2 => '周二', 3 => '周三', 4 => '周四', 5 => '周五', 6 => '周六'];
            //            $weekDay = date('w');
            // 将日期和星期几添加到数组中
            $dates[] = ['date' => $dateString, 'dayOfWeek' => $weekMap[$dayOfWeek]];
        }
        msg(0, '查询成功', $dates);
    }

    //接送服务详情
    public function jsDetail()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];

        $order_detail = Db::name('server3')->find();
        $order_detail['tag'] = explode(',', $order_detail['tag']);
        msg(0, '查询成功', $order_detail);
    }
    //接送评价顶部
    //接送评价列表

    //获取积分商品类型
    public function getGoodsCate2()
    {
        $data_list = Db::name('goods_categoty')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //获取积分商品列表
    public function getGoodsList()
    {
        // 0陪诊 1医疗用品 2优惠卷
        $data = $this->request->param();
        $cate_id = $data['cate_id'];
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $where[] = ['goods_cate', '=', $cate_id];
        $data_list = Db::name('goods')
            ->where($where)
            ->order('sort desc')
            ->page($page, $length)
            ->select();
        if ($cate_id == 2) {
            foreach ($data_list as $k => $v) {
                $coupons_info = Db::name('coupons')->find($v['object_id']);
                $data_list[$k]['value'] = $coupons_info['value'];
                $data_list[$k]['min_amount'] = $coupons_info['min_amount'];
                $data_list[$k]['effect_day'] = $coupons_info['effect_day'];
                $data_list[$k]['desc'] = $coupons_info['desc'];
            }
        } else if ($cate_id == 0) {
            foreach ($data_list as $k => $v) {
                $server_info = Db::name('server')->find($v['object_id']);
                $data_list[$k]['name'] = $server_info['name'];
                $data_list[$k]['img'] = $server_info['bc_img'];;
            }
        }
        msg(0, '查询成功', $data_list);
    }

    //获取商品详情
    public function getGoodsDetail()
    {
        //1优惠卷 2陪诊服务 3医疗用品
        //0陪诊 1医疗用品 2优惠卷
        $data = $this->request->param();
        $goods_id = $data['id'];
        $data_detail = Db::name('goods')->find($goods_id);
        if ($data_detail['goods_cate'] == 0) {
            $data_detail = Db::name('server')->find($data_detail['object_id']);
            $c_info = Db::name('goods')->find($goods_id);
            $data_detail['points'] = $c_info['points'];
            $data_detail['tag'] = explode(',', $data_detail['tag']);
            $data_detail['id'] = $goods_id;
        }
        if ($data_detail['goods_cate'] == 2) {
            $data_detail = Db::name('coupons')->find($data_detail['object_id']);
            $c_info = Db::name('goods')->find($goods_id);
            $data_detail['points'] = $c_info['points'];
            $data_detail['id'] = $goods_id;
        }
        msg(0, '查询成功', $data_detail);
    }

    public function getPzPeopleList()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $pz_list = Db::name('pz')->where([
            ['province|city', '=', $city],
            ['is_del', '=', 0],
            ['is_online', '=', 1],
            ['status', '=', 1],
            ['type', '=', 1]
        ])
            ->order('order_num desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                return $item;
            });
        msg(0, '查询成功', $pz_list);
    }

    //数据迁移
    public function toData()
    {
        $hospital_list = Db::name('yiyuan')->where([
            'parentid' => 0
        ])->select();
        foreach ($hospital_list as $k => $v) {
            $insert_data1 = array(
                'name' => $v['name'],
                'address' => $v['address'],
                'desc' => $v['description'],
                'tag' => $v['tags'],
                'create_time' => time(),
                'real_city' => $v['shi'],
                'sort' => $v['id']
            );
            $insert_hospital_data_id = Db::name('hospital')->insertGetId($insert_data1);
            $department1_list = Db::name('yiyuan')->where([
                'parentid' => $v['id']
            ])->select();
            foreach ($department1_list as $k2 => $v2) {
                $department1_insert = array(
                    'name' => $v2['name'],
                    'pid' => 0,
                    'sort' => $v2['id'],
                    'hospital_id' => $insert_hospital_data_id
                );
                $department1_insert_id = Db::name('department')->insertGetId($department1_insert);
                $department2_list = Db::name('yiyuan')->where([
                    'parentid' => $v2['id']
                ])->select();
                foreach ($department2_list as $k3 => $v3) {
                    $department2_insert = array(
                        'name' => $v3['name'],
                        'pid' => $department1_insert_id,
                        'sort' => $v3['id'],
                        'hospital_id' => $insert_hospital_data_id
                    );
                    $department2_insert_id = Db::name('department')->insertGetId($department2_insert);
                }

            }
        }
    }
    //todo 会员数量 陪导诊订单 陪诊类型 陪诊师
    // 陪诊金额 导诊金额 套餐金额 会员卡金额 已提现金额
    //index1 大屏接口
    public function cIndex()
    {
        //会员数量 陪导诊订单 陪诊类型 陪诊师
        $a = Db::name('member')
            ->where('openid', '<>', 0)
            ->count();
        $b = Db::name('server_order')->where([
            ['status', 'in', [2, 3, 4, 7, 8]]
        ])->count();
        $c = Db::name('server')->where([
            ['is_del', 'in', [0]]
        ])->count();
        $d = Db::name('pz')->where([
            ['status', 'in', [1, 2]],
            ['is_del', '=', 0]
        ])->count();
        $data['a'] = $a;
        $data['b'] = $b;
        $data['c'] = $c;
        $data['d'] = $d;
        msg(0, '查询更改', $data);
    }

    //index2
    public function cIndex2()
    {
        $a = Db::name('server_order')->where([
            ['status', 'in', [2, 3, 4, 7, 8]],
            ['order_type', '=', 1]
        ])->sum('pay_money');

        $b = Db::name('server_order')->where([
            ['status', 'in', [2, 3, 4, 7, 8]],
            ['order_type', '=', 2]
        ])->sum('pay_money');

        $c = Db::name('package_order')->where([
            ['status', 'in', [2]],
        ])->sum('pay_money');

        $d = Db::name('mcard_order')->where([
            ['status', 'in', [2]],
        ])->sum('pay_money');
        $e = Db::name('member_finance')->where([
            ['type', 'in', [4, 5, 6]],
            ['status', '=', 1],
            ['is_kuan', '=', 1]
        ])->sum('money');
        $data['a'] = $a;
        $data['b'] = $b;
        $data['c'] = $c;
        $data['d'] = $d;
        $data['e'] = $e;
        msg(0, '查询更改', $data);
    }

    public function getPie()
    {
        $return_data = array();
        $server_info = Db::name('server')->where([
            'is_del' => 0
        ])->select();
        foreach ($server_info as $k => $v) {
            $num = Db::name('server_order')->where([
                ['status', 'in', [2, 3, 4, 7, 8]],
                ['server_id', '=', $v['id']]
            ])->count();
            $return_data[$k]['name'] = $v['name'];
            $return_data[$k]['value'] = $num;
        }
        msg(0, '查询更改', $return_data);
    }

    public function getbar()
    {
        $pz_list = Db::name('pz')
            ->where([
                ['status', 'in', [1, 2]],
                ['is_del', 'in', [0]],
            ])
            ->order('order_num desc')
            ->limit(10)->select();
        $data1 = array();
        $data2 = array();
        foreach ($pz_list as $k => $v) {
            $data1[] = $v['name'];
            $data2[] = $v['order_num'];
        }
        $return_data['data1'] = $data1;
        $return_data['data2'] = $data2;
        msg(0, '查询更改', $return_data);
    }

    //陪诊导诊定时任务
    public function getOrderPay()
    {
        Db::startTrans();
        try {
            $limit = 60;
            $page = Cache::get('getAccount_page');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_page', $page);
            }
            $order_where = [
                ['status', '=', 1],//1待支付
            ];
            $order_list = Db::name('server_order')
                ->page($page, $limit)
                ->where($order_where)
                ->order('create_time desc')
                ->select();

            if (!$order_list) {
                $page = 1;
                Cache::set('getAccount_page', $page);
                msg(100, '订单为空', '');
            }
            Cache::set('getAccount_page', ++$page);
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            foreach ($order_list as $k => $item) {
                $res = $app->order->queryByOutTradeNumber($item['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    serverPaySuccess($item);
                }
            }
            Db::commit();
            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //车送定时任务完成
    public function getOrderPay2()
    {
        Db::startTrans();
        try {
            $limit = 60;
            $page = Cache::get('getAccount_page2');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_page2', $page);
            }
            $order_where = [
                ['status', '=', 1],//1待支付
            ];
            $order_list = Db::name('driver_order')
                ->page($page, $limit)
                ->where($order_where)
                ->order('create_time desc')
                ->select();

            if (!$order_list) {
                $page = 1;
                Cache::set('getAccount_page2', $page);
                msg(100, '订单为空', '');
            }
            Cache::set('getAccount_page2', ++$page);
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            foreach ($order_list as $k => $item) {
                $res = $app->order->queryByOutTradeNumber($item['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    driverPaySuccess($item);
                }
            }
            Db::commit();
            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //会员卡定时完成任务
    public function getOrderPay3()
    {
        Db::startTrans();
        try {
            $limit = 60;
            $page = Cache::get('getAccount_page3');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_page3', $page);
            }
            $order_where = [
                ['status', '=', 1],//1待支付
            ];
            $order_list = Db::name('mcard_order')
                ->page($page, $limit)
                ->where($order_where)
                ->order('create_time desc')
                ->select();

            if (!$order_list) {
                $page = 1;
                Cache::set('getAccount_page3', $page);
                msg(100, '订单为空', '');
            }
            Cache::set('getAccount_page3', ++$page);
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            foreach ($order_list as $k => $item) {
                $res = $app->order->queryByOutTradeNumber($item['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    if ($item['status'] == 1) {
                        $member_info = Db::name('member')->find($item['member_id']);
                        $mcard_list_id = vip($item['mcard_id'], $item['member_id']);
                        //更新订单状态
                        $update_mcard_order = array(
                            'id' => $item['id'],
                            'status' => 2,
                            'pay_time' => time(),
                            'mcard_list_id' => $mcard_list_id,
                            'fx_money' => getFxMoney($item, 4)
                        );
                        Db::name('mcard_order')->update($update_mcard_order);
                        addFraction(
                            $item['member_id'],
                            $item['pay_money'] * config('site.one_price_points'),
                            '会员卡订单：' . $item['order_no'],
                            3,
                            1,
                            '',
                            '',
                            $item['order_no'],
                            4
                        );
                        addFxMoney($item, 4, $member_info);
                    }
                }
            }
            Db::commit();
            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //购买套餐定时完成任务
    public function getOrderPay4()
    {
        Db::startTrans();
        try {
            $limit = 60;
            $page = Cache::get('getAccount_page4');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_page4', $page);
            }
            $order_where = [
                ['status', '=', 1],//1待支付
            ];
            $order_list = Db::name('package_order')
                ->page($page, $limit)
                ->where($order_where)
                ->order('create_time desc')
                ->select();

            if (!$order_list) {
                $page = 1;
                Cache::set('getAccount_page4', $page);
                msg(100, '订单为空', '');
            }
            Cache::set('getAccount_page4', ++$page);
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            foreach ($order_list as $k => $item) {
                $res = $app->order->queryByOutTradeNumber($item['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    if ($item['status'] == 1) {
                        //给用户发送套餐
                        $mp_id = giveMemberPackage2($item['package_id'], $item['member_id']);
                        //更新订单状态
                        $update_package_order = array(
                            'id' => $item['id'],
                            'status' => 2,
                            'pay_time' => time(),
                            'fx_money' => getFxMoney($item, 3),
                            'mp_id' => $mp_id
                        );
                        Db::name('package_order')->update($update_package_order);
                        //发送积分
                        addFraction(
                            $item['member_id'],
                            $item['pay_money'] * config('site.one_price_points'),
                            '套餐订单：' . $item['order_no'],
                            3,
                            1,
                            '',
                            '',
                            $item['order_no'],
                            3
                        );
                        addFxMoney($item, 3, $item['member_id']);
                    }
                }
            }
            Db::commit();
            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //陪诊导诊定时取消
    public function pdOrderCancel()
    {
        Db::startTrans();
        try {
            $order_list = Db::name('server_order')->where([
                'is_del' => 0,
                'status' => 1
            ])->select();
            foreach ($order_list as $k => $v) {
                //超过15分钟未支付为失效
                $a = time() - ($v['create_time'] + 15 * 60);
                if ($a >= 0) {
                    $update = array(
                        'id' => $v['id'],
                        'status' => 5,
                        'cancel_time' => time()
                    );
                    Db::name('server_order')->update($update);
                }
            }
            Db::commit();
            msg(0, '查询完成', date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //接送订单定时取消
    public function pdOrderCancel2()
    {
        Db::startTrans();
        try {
            $order_list = Db::name('driver_order')->where([
                'is_del' => 0,
                'status' => 1
            ])->select();
            foreach ($order_list as $k => $v) {
                //超过15分钟未支付为失效
                $a = time() - ($v['create_time'] + 15 * 60);
                if ($a >= 0) {
                    $update = array(
                        'id' => $v['id'],
                        'status' => 5,
                        'cancel_time' => time()
                    );
                    Db::name('driver_order')->update($update);
                }
            }
            Db::commit();
            msg(0, '查询完成', date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //会员卡订单定时取消
    public function pdOrderCancel3()
    {
        Db::startTrans();
        try {
            $order_list = Db::name('mcard_order')->where([
                'is_del' => 0,
                'status' => 1
            ])->select();
            foreach ($order_list as $k => $v) {
                //超过15分钟未支付为失效
                $a = time() - ($v['create_time'] + 15 * 60);
                if ($a >= 0) {
                    $update = array(
                        'id' => $v['id'],
                        'status' => 5,
                        'cancel_time' => time()
                    );
                    Db::name('mcard_order')->update($update);
                }
            }
            Db::commit();
            msg(0, '查询完成', date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //套餐订单定时取消
    public function pdOrderCancel4()
    {
        Db::startTrans();
        try {
            $order_list = Db::name('package_order')->where([
                'is_del' => 0,
                'status' => 1
            ])->select();
            foreach ($order_list as $k => $v) {
                //超过15分钟未支付为失效
                $a = time() - ($v['create_time'] + 15 * 60);
                if ($a >= 0) {
                    $update = array(
                        'id' => $v['id'],
                        'status' => 5,
                        'cancel_time' => time()
                    );
                    Db::name('package_order')->update($update);
                }
            }
            Db::commit();
            msg(0, '查询完成', date('Y-m-d H:i:s'));
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    public function c1()
    {
        $d1_list = Db::name('department')->where([
            'pid' => 0,
            'is_del' => 0
        ])->select();
        foreach ($d1_list as $k => $v) {
            $d2_list = Db::name('department')->where([
                'pid' => $v['id'],
                'is_del' => 0
            ])->select();
            if (!$d2_list) {
                $insert_data = array(
                    'name' => $v['name'],
                    'pid' => $v['id'],
                    'hospital_id' => $v['hospital_id']
                );
                Db::name('department')->insertGetId($insert_data);
            }
        }
    }

    //路线数据
    public function insertRoute()
    {
        $address = array(['上海站', 100, 200], ['虹桥火车站', 150, 300], ['上海南站', 150, 300], ['浦东机场', 300, 600]);
        $hospital_list = Db::name('hospital')->where(['is_del' => 0])->select();
        foreach ($hospital_list as $k => $v) {
            foreach ($address as $k2 => $v2) {
                $route = array(
                    'sort' => $k2 + 1,
                    'price' => $v2[1],
                    'd_price' => $v2[2],
                    'create_time' => time(),
                    'type' => 2,
                    'province2' => $v['province'],
                    'city2' => $v['city'],
                    'address' => $v2[0],
                    'hospital_id' => $v['id']
                );
                Db::name('route')->insertGetId($route);
            }
        }
    }

    //新订单
    public function index21()
    {

        $server_list_id = Db::name('server_order')->where([
            ['status', 'in', [2, 7]],
            ['is_show', '=', 0]
        ])->column('id');
        if ($server_list_id) {
            Db::name('server_order')->where('id', 'in', $server_list_id)->update([
                'is_show' => 1
            ]);
            return json(['code' => 0, 'data' => count($server_list_id), 'msg' => '获取成功']);

        } else {
            return json(['code' => -1, 'data' => '', 'msg' => '获取成功']);
        }
    }
    //支付宝初始化
    public static function appInit($type = 0)
    {

        $data = [
            'appid' => '2021005100634222',
            'encryptKey' => 'ruwU8hf2SvNwSfgLNjZo4w==',
            'gateway' => 'https://openapi.alipay.com/gateway.do',
            'private_key' => 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCwvk+U0e98BoS0y659n+PXuDsLvDv6h/YLI3HmEhbHMH692ZgbdFvOoc7y4kONjiZrBqAAnmnwY9Sv9I0r7L26/DpJyd8ESZmQ7QaDgCWXIEd1cXxuF0bYpsbei/FXKp2tedW+R0HJcLvaH+/l+uVQJGFxvngyq5C5GC4Ft5vgJeouNRpDxw7SQNh2FZmdQPaZcPS9uz76YPQIsZWp9kssy3NQKMHcEoWPfWLIP9QU7046jrPx87EDynx/v7XCHxPUXc82FMDhulSbDX+93A0vMOg1Zecc33g/RS6OYMbbWWzOJJtCs8UK9jtgPjpYcdkU6K5gkZ0OgCjarXE3D0hTAgMBAAECggEAevRqOIWzrPx75aqswQgyYSfxK8DPmQJs0GLgIcYDwp6iDUEK6E6Sb7VxWta9WATEBUCens+Vs34/wAjJDP2tIB/IDP07AKiTBJdgKKtFe1UhYTqJ7ayTxLSBNOD2DEXBW6WeZLj9sz2R8bS2F6/rR02H3LE8vUNNcva3TZLmBZAywSXGv5yuGZi5fpO8I7s2+GjqPRmz1WMp4z66D6q2Bw0WMb5F2RanWEtgtHd5wx9hAdFNeflrN8xxNY/okz6f8BdzqXuALwvsRvRzjCtS0Nb8qSvBv9yC2DZNTvqdl9yE1NlPGkYWhwCSGIPSmG1FzaVvPs78308j9giuSKz0AQKBgQDag/edyVUKI2psv9PHgyZVjoXpqXXVTKeQT69nIwCRfilZDTr5A2/0FGBY2n6OzmwKlwZT2BndxYysXGkxZw3GBx4/cOathmLbCcEU4jAKC4b1TjbQ/LGGzgJPKcZ6tg6JaudlPRyvW/B1Gxv94FPYbDVO+2ZlHzYJn4FsTiYHEwKBgQDPD++64xcRXDDq4oTfCr61DoMsSUy6w72duTrL2LuREH8rj/EcZry1mkXSGAYZJjVwdl//Apaj73QSKM/bWS947qwc0HWrQzJOpxSoTi4EVCriPJ6m1pCplqxb7UuSV4vcgdcV1sEUnzc5tXIht8USElWvx0jM2siNy6dvf2uhwQKBgHOni2SBDjh6fDao5S9g8+YutCPzJEHL+5g/BMhi10cqbjoK7Z6kuhmGu2Pr6TYufTKxspCn/TDLAWSs2KRkNf8M/252lDFdwm7KX95sxR5b8YdeaVb9l/yQhtpdcwa520HSSjzkNo197OweeBdMJzSSOTjfiNeWyGQZf0fSqP/vAoGAUHCsfToDmCbsihN98vhFpikBJI9FU7j/TOrMwKxuEakK/m1pCdOPtC0+uqPCmrqRQCN8n6DtzLoVqYhZV6mKG7z8+CSz0djFDnEyQUA9+EiKcGGEcOQiRv/V7dB971g7aWq3mDBZyh0gYzbuI9M0qBSfXS5aRdso1o0retFRiwECgYAy3YRChjF4DbWoV7+O56fnA+TE2z3J2Ef6dwgs6ppJ/pqIyPgNvsWdKSuM8W5BaytMcuFbA76hg3vWoJm8AXQ5tCk7kzl7I6UevMoaBX1emn8Yi9pAmbG5yXYAgr4/u8Plq/cpgl5T6j562q6IR0mmfCjQiKGJetLIfyrw8YXQZw==',
            'alipay_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7pXctJBsRPPCKAZXEIs9wawj4c2nSRDwDVMwjgGjhi5guRq90KdT8MxWUOpn3EilIQohKvl7f7odK+t7ElClZbPRhGtO0+GwOq8Dz6TngtqMa7OOkoRZLdJ2Cqr+mw06Ia2VkrNwzJ52eJPKC45WsDnJnvTRU8DcyNOdvIuJ2R5uoEQVM/wvq03yDLukIsgagC43FMMFA6EhKsthsaVQPAEDyOjKDZj0nlCnqPhTPR+OShNQq7+OUz/R/b1lDUoLhfqm95F6QgkEkOx99GZB2LKbDXBf0tE1IROX+Nqqq45dozNOSXFHth/q21e+22/0beTqlImRFHxtomrzF+4J2QIDAQAB'
        ];
        $config = new Config();
        $config->protocol = 'https';
        $config->gatewayHost = 'openapi.alipay.com';
        $config->signType = 'RSA2';
//        $config->signType = 'AES';
        $config->appId = $data['appid'];
        $config->merchantPrivateKey = $data['private_key'];
        $config->alipayPublicKey = $data['alipay_public_key'];
        $config->encryptKey = $data['encryptKey'];

        AlipayFactory::setOptions($config);
//        return Factory::base();
    }

    //获取openid
    public function aliPaylogin()
    {
        $code = $this->request->param("code");
//        $code='2b49c75a70ff4f368d831276407eWC97';
        self::appInit();
        $result = AlipayFactory::base()->oauth()->getToken($code);
//        dump($result) ;
        msg(0,'查询完成',json_decode($result->httpBody,true));
//        return $result->httpBody;
    }
    //支付宝获取手机号
    public  function aliPayPhone()
    {
        $data = $this->request->param('decrypt','', null);
//       $decrypt = "0Iz8ApNNWDDbF+iOV1fhW8u6Ad1fMn0snZQezEmGqP/eN59zpElaoutz4SDZb4vlFUfjlmaCT7RC7QbrVEPBjA==";
//        dump($decrypt);
//        dump($data);
//        die;
        self::appInit();
        $res = AlipayFactory::util()->aes()->decrypt($data);
//        $res = AlipayFactory::util()->aes()->decrypt($decrypt);
        msg(0,'查询完成',json_decode($res,true));
    }
    //服务支付异步回调
    public function payServerOrderAliBack(){
        $arr = $_POST;
        $return =json_encode($arr);
        Db::name('pay_log')->insertGetId([
            'time'=>time(),
            'order_c'=>$_POST['out_trade_no'],
            'desc'=>'payServerOrderAliBack-服务支付异步回调',
            'content'=>$return
        ]);
        self::appInit();
        $result=AlipayFactory::payment()->common()->verifyNotify($arr);
        if ($result){
            if ($arr['trade_status']=='TRADE_SUCCESS'){
                $order_no = $arr['out_trade_no'];
                $order_data = Db::name('server_order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                if ($order_data['status'] == 1) {
                    serverPaySuccess($order_data, 4);
                }
            }
            echo "success";	//请不要修改或删除
        }else{
            //验证失败
            echo "fail";
        }
    }
    //接送订单发起支付异步回调
    public function payDriverOrderAliBack(){
        $arr = $_POST;
        $return =json_encode($arr);
        Db::name('pay_log')->insertGetId([
            'time'=>time(),
            'order_c'=>$_POST['out_trade_no'],
            'desc'=>'payDriverOrderAliBack-接送订单发起支付异步回调',
            'content'=>$return
        ]);
        self::appInit();
        $result=AlipayFactory::payment()->common()->verifyNotify($arr);
        if ($result){
            if ($arr['trade_status']=='TRADE_SUCCESS'){

                $order_no = $arr['out_trade_no'];
                $order_data = Db::name('driver_order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                if ($order_data['status'] == 1) {
                    driverPaySuccess($order_data, 4);
                }
            }
            echo "success";	//请不要修改或删除
        }else{
            //验证失败
            echo "fail";
        }

//        //todo 回调
//        $arr = $_POST;
////        $string='{"gmt_create":"2025-08-01 08:58:41","charset":"UTF-8","seller_email":"lepaowangluo@163.com","subject":"\u966a\u8bca\u670d\u52a1","sign":"AMcInqaCBcLy43srMjSgBJfCr+RD2unetrDXkiHl2\/X7MYg+6+Bf1wUpLKu1BHcvUybMFu8pD4D6frAkhCVfziZ\/T7o3zU7SpO0cbUi2xbhP3rmIAgHfMIsengSvVFKDwdgTHtr4u+74EtS0i98lskvJh39AlUc6lDWpjITiSwD3cZtWlCVnJYqt8Z+ZRs798HYx0T9lSBonzfCw3axOBE9OYSasQrMSCMC4S\/RvxH2gqo95GlTmbirQpB\/SumuyizwozdPVTU2hmyIjVhzjEBq21Pss5Ii0tm4Jw\/N\/X\/GapfKvTrLCRNBg2D00LkTOjl6qtYjJVFZEh7jbEb1YVg==","buyer_open_id":"0971Bp9d8S3AN390gSvm65qSELLJJ_dg48XN2bOvnL9DSg2","invoice_amount":"0.01","notify_id":"2025080101222085851070971460233021","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","buyer_pay_amount":"0.01","app_id":"2021005100634222","sign_type":"RSA2","seller_id":"2088411625474671","gmt_payment":"2025-08-01 08:58:50","notify_time":"2025-08-01 12:25:26","merchant_app_id":"2021005100634222","version":"1.0","out_trade_no":"20250801085840880835322","total_amount":"0.01","trade_no":"2025080122001470971455495181","auth_app_id":"2021005100634222","buyer_logon_id":"177****9223","point_amount":"0.00"}';
////        dump(json_decode($string,true));
////        $arr=json_decode($string,true);
//        self::appInit();
//        $result=AlipayFactory::payment()->common()->verifyNotify($arr);
//        if ($result){
//
//
//            echo "success";	//请不要修改或删除
//        }else{
//            //验证失败
//            echo "fail";
//        }
//      //  dump($verify_data);
//        die;
//        $return =json_encode($arr);
//        $order= GetOrderSN(2);
//        Db::name('pay_log')->insertGetId([
//            'time'=>time(),
//            'order_c'=>$order,
//            'desc'=>'1'
//        ]);
//        Db::name('pay_log')->insertGetId([
//            'time'=>time(),
//            'order_c'=>$order,
//            'desc'=>'payDriverOrderAliBack-服务支付回调',
//            'content'=>$return
//        ]);
    }
    //发起套餐支付宝发异步回调
    public function packageOrderBackAliBack(){
        $arr = $_POST;
        $return =json_encode($arr);
        Db::name('pay_log')->insertGetId([
            'time'=>time(),
            'order_c'=>$_POST['out_trade_no'],
            'desc'=>'packageOrderBackAliBack-发起套餐支付宝发异步回调',
            'content'=>$return
        ]);
        self::appInit();
        $result=AlipayFactory::payment()->common()->verifyNotify($arr);
        if ($result){
            if ($arr['trade_status']=='TRADE_SUCCESS'){
                $order_no = $arr['out_trade_no'];
                $order_data = Db::name('package_order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                if ($order_data['status'] == 1) {
                    //给用户发送套餐
                    $mp_id = giveMemberPackage2($order_data['package_id'], $order_data['member_id']);
                    //更新订单状态
                    $update_package_order = array(
                        'id' => $order_data['id'],
                        'status' => 2,
                        'pay_time' => time(),
                        'fx_money' => getFxMoney($order_data, 3),
                        'mp_id' => $mp_id,
                        'pay_type' => 4
                    );
                    Db::name('package_order')->update($update_package_order);
                    //发送积分
                    addFraction(
                        $order_data['member_id'],
                        $order_data['pay_money'] * config('site.one_price_points'),
                        '套餐订单：' . $order_data['order_no'],
                        3,
                        1,
                        '',
                        '',
                        $order_data['order_no'],
                        3
                    );
                    $member_info=Db::name('member')->find($order_data['member_id']);
                    addFxMoney($order_data, 3,$member_info);
                }
            }
            echo "success";	//请不要修改或删除
        }else{
            //验证失败
            echo "fail";
        }
    }
    //会员卡支付宝发起支付异步回调
    public function payVipOrderAliBack(){
        $arr = $_POST;
        $return =json_encode($arr);
        Db::name('pay_log')->insertGetId([
            'time'=>time(),
            'order_c'=>$_POST['out_trade_no'],
            'desc'=>'payVipOrderAliBack-会员卡支付宝发起支付异步回调',
            'content'=>$return
        ]);
        self::appInit();
        $result=AlipayFactory::payment()->common()->verifyNotify($arr);
        if ($result){
            if ($arr['trade_status']=='TRADE_SUCCESS'){
                $order_no =  $arr['out_trade_no'];
                $order_data = Db::name('mcard_order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                if ($order_data['status'] == 1) {
                    $mcard_list_id = vip($order_data['mcard_id'], $order_data['member_id']);
                    //更新订单状态
                    $update_mcard_order = array(
                        'id' => $order_data['id'],
                        'status' => 2,
                        'pay_time' => time(),
                        'mcard_list_id' => $mcard_list_id,
                        'fx_money' => getFxMoney($order_data, 4),
                        'pay_type' => 4,
                    );
                    Db::name('mcard_order')->update($update_mcard_order);
                    addFraction(
                        $order_data['member_id'],
                        $order_data['pay_money'] * config('site.one_price_points'),
                        '会员卡订单：' . $order_data['order_no'],
                        3,
                        1,
                        '',
                        '',
                        $order_data['order_no'],
                        4
                    );
                    $member_info=Db::name('member')->find($order_data['member_id']);
                    addFxMoney($order_data, 4,$member_info);
                }
            }
            echo "success";	//请不要修改或删除
        }else{
            //验证失败
            echo "fail";
        }
    }

    //支付宝退款
    public function refundAli()
    {
        $data = $this->request->param();
        self::appInit();
        $result = AlipayFactory::util()->generic()->execute(
            'alipay.trade.refund',
            [], [
                'out_trade_no' => $data['order_no'], // 订单号
                'refund_amount' => '0.01', // 退款订单号
            ]
        );

        $resultArray = json_decode($result->httpBody, true);
        msg(1,'',$resultArray);
        dump($resultArray);
        die;
        return json_encode($result->httpBody,true);
    }


}
